﻿//获取和存储文件
var request = require('request'),
    https = require('https'),
    http = require('http'),
    fs = require("fs");
    Log = require("./Log.js");


function getAndSaveFile(imgUrl, savePath, fileName) {
    Log.info("getAndSaveImg:" + imgUrl);
    http.get(imgUrl, function (res) {
        try {
            var imgData = "";

            res.setEncoding("binary"); //一定要设置response的编码为binary否则会下载下来的图片打不开

            try {
                res.on("data", function (chunk) {
                    imgData += chunk;
                });
            } catch (e) {
                Log.error("data error : " + e);
            }

            try {
                res.on("end", function () {
                    try {
                        fs.writeFile(savePath + fileName, imgData, "binary", function (err) {
                            if (err) {
                                Log.error(fileName + " down fail");
                            }
                            Log.info(fileName + " down success");
                        });
                    } catch (e) {
                        Log = require("./Log.js");("saveFile error : " + e);
                    }
                });
            } catch (e) {
                Log.error("res.end error : " + e);
            }

            res.on("error", function (error) {
                Log.error("ERROR:" + error);
            });
        } catch (e) {
            Log.error("inside DownLoad Fail :" + imgUrl);
            Log.error(e);
        }
    });
}

module.exports = getAndSaveFile;